package com.waterworld.watch.home.activity;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.waterworld.watch.R;
import com.waterworld.watch.common.activity.BaseActivity;
import com.waterworld.watch.common.bean.AddressBookBean;
import com.waterworld.watch.common.bean.IntimateSetBean;
import com.waterworld.watch.common.bean.UserInfoBean;
import com.waterworld.watch.common.net.BaseObserverListener;
import com.waterworld.watch.common.net.BaseResultBean;
import com.waterworld.watch.common.util.ScreenAdapterUtil;
import com.waterworld.watch.common.util.ToastUtils;
import com.waterworld.watch.home.adapter.SkillContactListAdapter;
import com.waterworld.watch.home.event.AddressBookEvent;
import com.waterworld.watch.home.interfaces.IHomeManager;
import com.waterworld.watch.home.manager.HomeManager;


import com.waterworld.watch.mine.interfaces.IMineManager;
import com.waterworld.watch.mine.manager.MineManager;
import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;

import static com.alibaba.fastjson.JSON.toJSONString;

public class SkillContactListActivity extends BaseActivity implements View.OnClickListener {

    @BindView(R.id.header_parent)
    LinearLayout header_parent;

    @BindView(R.id.header_back)
    ImageView header_back;

    @BindView(R.id.header_title)
    TextView header_title;

    @BindView(R.id.header_add)
    ImageView header_add;

    @BindView(R.id.rl_blackList)
    RelativeLayout rl_blackList;

    @BindView(R.id.rv_contact_recycler)
    RecyclerView contactRecycler;

    @BindView(R.id.cb_blackList)
    CheckBox switchBlack;

    @BindView(R.id.btn_submit)
    Button btnSubmit;

    private IHomeManager iHomeManager = HomeManager.getInstance();
    private IMineManager iMineManager = MineManager.getInstance();
    private List<AddressBookBean> contactData;
    private SkillContactListAdapter contactAdapter;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_skill_contact);
        ButterKnife.bind(this);
        initView();
        initData();
        EventBus.getDefault().register(this);
    }

    private void initView() {
        setViewSize(header_parent, ViewGroup.LayoutParams.MATCH_PARENT, ScreenAdapterUtil.getHeightPx(this) / 10);
        header_title.setText(getString(R.string.watch_address_book));
        header_back.setVisibility(View.VISIBLE);
        header_title.setVisibility(View.VISIBLE);
        if (UserInfoBean.getInstance().getWatchUser().getUserRole() == 0) {
            header_add.setVisibility(View.VISIBLE);
            btnSubmit.setVisibility(View.VISIBLE);
            rl_blackList.setVisibility(View.VISIBLE);
        }
        header_back.setOnClickListener(this);
        header_add.setOnClickListener(this);
        btnSubmit.setOnClickListener(this);
        switchBlack.setOnClickListener(this);
    }

    private void initData() {
        switchBlack.setChecked(IntimateSetBean.getInstance().isShieldStrangeCall());
        contactData = new ArrayList<>();
        if (iHomeManager != null) {
            iHomeManager.listAddressBook(new BaseObserverListener<BaseResultBean<AddressBookBean[]>>() {
                @Override
                public void onCompleted() {
                }

                @Override
                public void onError(Throwable e) {
                    ToastUtils.showShort(SkillContactListActivity.this, getString(R.string.data_error));
                }

                @Override
                public void onNext(BaseResultBean<AddressBookBean[]> baseResultBean) {
                    AddressBookBean[] addressBooks = baseResultBean.getData();
                    contactData.addAll(Arrays.asList(addressBooks));
                    contactAdapter = new SkillContactListAdapter(SkillContactListActivity.this, contactData);
                    contactRecycler.setLayoutManager(new LinearLayoutManager(SkillContactListActivity.this, LinearLayoutManager.VERTICAL, false));
                    contactRecycler.setAdapter(contactAdapter);
                    if (UserInfoBean.getInstance().getWatchUser().getUserRole() == 0) {
                        contactAdapter.setOnContactClickListener(new SkillContactListAdapter.onContactClickListener() {
                            @Override
                            public void contactClick(View view, int position) {
                                startActivity(new Intent(SkillContactListActivity.this, SkillContactInfoActivity.class).putExtra("contacts", contactData.get(position)).putExtra("position", position));
                            }
                        });
                    }
                }
            });
        }


    }

    @Override
    public void onClick(View view) {
        switch (view.getId()){
            case R.id.header_back:
                finish();
                break;
            case R.id.header_add:
                startActivity(new Intent(this,SkillContactInfoActivity.class).putExtra("position",contactData.size()));
                break;
            case R.id.btn_submit:
                if (iHomeManager != null) {
                    StringBuilder sb = new StringBuilder();
                    sb.append("{addressBook:[");
                    for (AddressBookBean bean : contactData) {
                        Map<String,String> map = new HashMap<>();
                        map.put("phone",bean.getPhone());
                        map.put("name",bean.getName());
                        map.put("head",bean.getHead());
                        map.put("role",bean.getRole());
                        sb.append(JSON.toJSONString(map)+",");
                    }
                    sb = new StringBuilder(sb.substring(0,sb.length()-1));
                    sb.append("]}");
                    Log.e("nh",sb.toString());
                    iHomeManager.uploadAddressBook(sb.toString(), new BaseObserverListener() {
                        @Override
                        public void onCompleted() {
                            ToastUtils.showShort(SkillContactListActivity.this,getString(R.string.upload_success));
                        }

                        @Override
                        public void onError(Throwable e) {

                        }

                        @Override
                        public void onNext(Object o) {
                        }
                    });
                }

                if (iMineManager != null) {
                    iMineManager.updateIntimateSet(null, null, null, null,switchBlack.isChecked() , null, null, null, null, null, null, new BaseObserverListener() {
                        @Override
                        public void onCompleted() {
                            IntimateSetBean.getInstance().setShieldStrangeCall(switchBlack.isChecked());
                        }

                        @Override
                        public void onError(Throwable e) {

                        }

                        @Override
                        public void onNext(Object o) {

                        }
                    });
                }
                break;
            case R.id.cb_blackList:
                break;
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void updateAddressBook (AddressBookEvent event) {
        if (event.getDelete()) {
            //删除联系人
            contactData.remove(event.getPosition());
        }else {
            if (event.getPosition() >= contactData.size()) {
                //新增联系人
                AddressBookBean bean = event.getAddressBookBean();
                contactData.add(bean);
            } else {
                //修改联系人
                AddressBookBean bean = contactData.get(event.getPosition());
                bean.setHead(event.getAddressBookBean().getHead());
                bean.setName(event.getAddressBookBean().getName());
                bean.setPhone(event.getAddressBookBean().getPhone());
                bean.setRole(event.getAddressBookBean().getRole());
            }
        }
        contactAdapter.notifyDataSetChanged();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().unregister(this);
        }
    }
}
